/**
 * 
 */
package com.lurencun.android.topicbank.ui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.j256.ormlite.dao.Dao;
import com.lurencun.android.support.ui.BackUIActivity;
import com.lurencun.android.support.widget.CommonAdapter;
import com.lurencun.android.topicbank.AppSetting;
import com.lurencun.android.topicbank.R;
import com.lurencun.android.topicbank.entity.AnswerJsonEntity;
import com.lurencun.android.topicbank.entity.PaperJsonEntity;
import com.lurencun.android.topicbank.entity.PaperPurchased;
import com.lurencun.android.topicbank.entity.SolutionJsonEntity;
import com.lurencun.android.topicbank.entity.TechniqueJsonEntity;
import com.lurencun.android.topicbank.entity.TopicJsonEntity;
import com.lurencun.android.topicbank.http.HttpHandler;
import com.lurencun.android.topicbank.http.RequestParams;
import com.lurencun.android.topicbank.presist.Answer;
import com.lurencun.android.topicbank.presist.DataHelper;
import com.lurencun.android.topicbank.presist.Paper;
import com.lurencun.android.topicbank.presist.Profile;
import com.lurencun.android.topicbank.presist.Solution;
import com.lurencun.android.topicbank.presist.Technique;
import com.lurencun.android.topicbank.presist.Topic;
import com.lurencun.android.topicbank.res.PaperAdapter;
import com.lurencun.android.topicbank.util.CommonUtil;
import com.lurencun.android.topicbank.util.DESEncrypt;
import com.lurencun.android.topicbank.util.GsonUtil;
import com.lurencun.android.topicbank.util.HttpUtil;
import com.lurencun.android.topicbank.util.MD5;
import com.lurencun.android.topicbank.util.ProfileUtil;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-24
 */
public class CategoryActivity extends BackUIActivity {

	private Context mContext;
	private DataHelper dataHelper;
	private Profile profile;
	
	@Override
	protected void onCreateEx(Bundle savedInstanceState) {
		mContext = this;
		dataHelper = new DataHelper(mContext);
		Intent intent = getIntent();
		String title = intent.getStringExtra(AppSetting.MENU_TITLE);

		TextView titleView = (TextView) findViewById(R.id.app_title);
		titleView.setText(title);
		profile = ProfileUtil.getInstance().hasProfile(mContext);
		
		// 网络可用
		if (CommonUtil.isNetworkAvailable(mContext)) {
			loadPapers(profile);
		}
		else {
			loadLocalPaperList();
		}
	}
	
	private void loadLocalPaperList() {
		Log.d("------", "loadLocalPaperList");
		ListView list = (ListView) findViewById(R.id.list_container);
		CommonAdapter<Paper> adapter;
		try {
			Dao<Paper, Long> paperDao = getHelper().getPaperDao();
			List<Paper> pList = paperDao.queryForAll();
			
			for (Paper paper : pList) {
				Log.d("------", "paper:" + paper);
			}
			adapter = new PaperAdapter(this, adapterHandler);
			adapter.updateDataCache(pList);
			list.setAdapter(adapter);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});
		
	}

	// 接收adapter点击事件
	final Handler adapterHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			System.out.println("adapterHandler handle:" + msg.obj.toString());
			switch (msg.what) {
				case 0:
					if (!CommonUtil.isNetworkAvailable(mContext)) {
						Toast.makeText(mContext,
								"network unreachable. please check the network...",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(mContext, msg.obj.toString(),
								Toast.LENGTH_SHORT).show();
					}
				break;
			}

		}
	};

	/**
	 * 同步试卷列表
	 * @param paperJson
	 */
	private void handleSyncPapers(String paperJson) {
		try {
			Map<String, Object> map = GsonUtil.getInstance().stm(paperJson);
			String papers = GsonUtil.getInstance().otj(map.get("papers"));
			List<PaperJsonEntity> paperList = GsonUtil.getInstance().stl(
					papers,
					new TypeToken<List<PaperJsonEntity>>() {
					}.getType());
			
			String purchased = GsonUtil.getInstance().otj(map.get("paperPurchased"));
			
			List<PaperPurchased> paperPurchased = GsonUtil.getInstance().stl(
					purchased,
					new TypeToken<List<PaperPurchased>>() {
					}.getType());
			
			Dao<Paper, Long> paperDao = getHelper().getPaperDao();
			Dao<Topic, Long> topicDao = getHelper().getTopicDao();
			Dao<Answer, Long> answerDao = getHelper().getAnswerDao();
			Dao<Solution, Long> solutionDao = getHelper().getSolutionDao();
			Dao<Technique, Long> techniqueDao = getHelper().getTechniqueDao();
			// 编列试卷列表
			Iterator<PaperJsonEntity> pit = paperList.iterator();
			while(pit.hasNext()) {
				PaperJsonEntity paperEntity = pit.next();
				List<TopicJsonEntity> topiclist = paperEntity.getTopics();
				
				checkPurchased(paperEntity, paperPurchased);
				List<Paper> localPaper = paperDao.queryBuilder().where().eq("paperId",paperEntity.getPaperId()).query();
				if (localPaper != null && localPaper.size() > 0) {
					Paper paper = localPaper.get(0);
					paperEntity.transform(paper);
					Log.d("------", "paper has been exsit." + paper);
					// 更新试卷
					paperDao.update(paper);
					// 更新试卷问题
					for (TopicJsonEntity topicJsonEntity : topiclist) {
						if (topicJsonEntity!=null && topicJsonEntity.isValid()) {
							Topic topic = topicJsonEntity.transform();
							topic.setPaper(paper);
							List<Topic> localTopic = topicDao.queryBuilder().where().eq("topicId", topic.getTopicId()).query();
							if (localTopic != null && localTopic.size() > 0) {
								topic.setId(localTopic.get(0).getId());
								topicDao.update(topic);
								Log.d("------", "update topic" + topic);
							}
							else {
								topicDao.create(topic);
								Log.d("------", "create topic" + topic);
							}
							answerDao.delete(topic.getAnswers());
							List<AnswerJsonEntity> answerList = topicJsonEntity.getAnswers();
							for (AnswerJsonEntity answerJsonEntity : answerList) {
								if (answerJsonEntity.isValid()) {
									Answer answer = answerJsonEntity.transform();
									answer.setTopic(topic);
									answerDao.create(answer);
								}
							}
							solutionDao.delete(topic.getSolution());
							SolutionJsonEntity solutionEntity = topicJsonEntity.getSolutions();
							if (solutionEntity!=null && solutionEntity.isValid()) {
								Solution solution = solutionEntity.transform();
								solution.setTopic(topic);
								solutionDao.create(solution);
							}
							techniqueDao.delete(topic.getTechnique());
							TechniqueJsonEntity techniqueEntity = topicJsonEntity.getTechniques();
							if (techniqueEntity!=null && techniqueEntity.isValid()) {
								Technique technique = techniqueEntity.transform();
								technique.setTopic(topic);
								techniqueDao.create(technique);
							}
						}
					}
				}
				else {
					Paper paper = paperEntity.transform();
					Log.d("------", "add new paper." + paper);
					// 添加试卷
					paperDao.create(paper);
					// 添加试卷问题
					for (TopicJsonEntity topicJsonEntity : topiclist) {
						if (topicJsonEntity!=null && topicJsonEntity.isValid()) {
							Topic topic = topicJsonEntity.transform();
							topic.setPaper(paper);
							List<Topic> localTopic = topicDao.queryBuilder().where().eq("topicId", topic.getTopicId()).query();
							if (localTopic != null && localTopic.size() > 0) {
								topic.setId(localTopic.get(0).getId());
								topicDao.update(topic);
								Log.d("------", "update topic" + topic);
							}
							else {
								topicDao.create(topic);
								Log.d("------", "create topic" + topic);
							}
							List<AnswerJsonEntity> answerList = topicJsonEntity.getAnswers();
							for (AnswerJsonEntity answerJsonEntity : answerList) {
								if (answerJsonEntity.isValid()) {
									Answer answer = answerJsonEntity.transform();
									answer.setTopic(topic);
									answerDao.create(answer);
								}
							}
							SolutionJsonEntity solutionEntity = topicJsonEntity.getSolutions();
							if (solutionEntity!=null && solutionEntity.isValid()) {
								Solution solution = solutionEntity.transform();
								solution.setTopic(topic);
								solutionDao.create(solution);
							}
							TechniqueJsonEntity techniqueEntity = topicJsonEntity.getTechniques();
							if (techniqueEntity!=null && techniqueEntity.isValid()) {
								Technique technique = techniqueEntity.transform();
								technique.setTopic(topic);
								techniqueDao.create(technique);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void checkPurchased(PaperJsonEntity paperEntity, List<PaperPurchased> paperPurchased) {
		Iterator<PaperPurchased> ppit = paperPurchased.iterator();
		while (ppit.hasNext()) {
			PaperPurchased purchased = ppit.next();
			if (paperEntity.getPaperId() == purchased.getPaper_id()) {
				paperEntity.setPurchased(true);
				break;
			}
		}
	}
	
	

	/**
	 * 查询试卷列表
	 * @param profile
	 */
	private void loadPapers(Profile profile) {

		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				handleSyncPapers(obj);
				loadLocalPaperList();
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
				Log.e("------", obj);
				loadLocalPaperList();
			}

		};
		
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(profile.getAndroidID() + "" + hexRandom);
		
		RequestParams params = new RequestParams();
//		params.put("uid", 1);
//		params.put("key", md5Key);
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "200");
		params.put("req", GsonUtil.getInstance().otj(reqMap));
		try {
			HttpUtil.getInstance().post("http://210.209.125.85/ocmba/dis.do", params, paperHttpHandler);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private DataHelper getHelper() {
		return dataHelper;
	}

	@Override
	protected int getContentViewLayoutId() {
		return R.layout.category;
	}

	@Override
	protected int getBackButtonResId() {
		return R.id.back_button;
	}

	@Override
	protected boolean isConfirmBack() {
		return false;
	}

}
